package edu.fjnu.order.utils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public final class JdbcUtils {
	private static JdbcUtils instance = null;
	private static String URL = null;
	private static String USER = null;
	private static String PASSWORD = null;
	
	/*
	 * 获得实例
	 */
	public static JdbcUtils getInstance(){
		if(instance == null){
			
			synchronized (JdbcUtils.class) {
				if(instance == null){
					
					instance = new JdbcUtils();
					instance.load();
				}
			}
		}
		return instance;
	}
	/*
	 * 获取sql连接
	 */
 	public Connection getConnection() throws SQLException{
		return DriverManager.getConnection(URL, USER, PASSWORD);
	}
	
 	/*
 	 * 加载连接sql所需要参数
 	 */
	private void load(){
		try {
			
			Properties props = new Properties();
			InputStream in = JdbcUtils.class.getResourceAsStream(
					"/edu/fjnu/order/database.properties");
			props.load(in);
			in.close();
			
			String drivers = props.getProperty("DBDRIVER");
			Class.forName(drivers).newInstance();
			URL = props.getProperty("DBURL");
			USER = props.getProperty("DBUSER");
			PASSWORD = props.getProperty("DBPWD");
		} catch (Exception e){
			
			e.printStackTrace();
		}
	}
	
	/*
	 * 释放sql资源
	 */
	public static void free(ResultSet rs, Statement st, Connection conn){
		
		try {
			if(rs != null)
				try {
					rs.close();
				} catch (SQLException e) {
					
					e.printStackTrace();
				}
		} finally {
			try{
				if(st != null)
					try {
						st.close();
					} catch (SQLException e) {
						
						e.printStackTrace();
					}
			}finally {
				if(conn != null){
					
					try {
						
						conn.close();
					} catch (SQLException e) {
						
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	/*
	 * 私有构成函数
	 */
	private JdbcUtils(){}
}
